package org.dromara.bykt.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HtmlUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.dromara.bykt.domain.bo.BYKTCourseExerciseBo;
import org.dromara.bykt.domain.bo.BYKTExamInfoBo;
import org.dromara.bykt.domain.vo.BYKTCourseExerciseImportVo;
import org.dromara.bykt.domain.vo.BYKTCourseExerciseVo;
import org.dromara.bykt.domain.vo.BYKTExamInfoImportVo;
import org.dromara.bykt.domain.vo.BYKTExamInfoVo;
import org.dromara.bykt.service.*;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.excel.core.ExcelListener;
import org.dromara.common.excel.core.ExcelResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class BYKTExamInfoImportListener extends AnalysisEventListener<BYKTExamInfoImportVo> implements ExcelListener<BYKTExamInfoImportVo> {

    private final IBYKTExamInfoService examInfoService;

    private final IBYKTGeographyInfoService geographyInfoService;

    private final Boolean isUpdateSupport;

    private final Map<String, String> pictureMap;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public BYKTExamInfoImportListener(Boolean isUpdateSupport, Map<String, String> pictureMap) {
        this.examInfoService = SpringUtils.getBean(IBYKTExamInfoService.class);
        this.geographyInfoService = SpringUtils.getBean(IBYKTGeographyInfoService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.pictureMap = pictureMap;
    }

    @Override
    public void invoke(BYKTExamInfoImportVo examInfoImportVo, AnalysisContext context) {
        BYKTExamInfoVo examInfoVo = this.examInfoService.selectText(examInfoImportVo.getTitle());
        // 获取当前行的图片索引（需要根据实际情况调整）
        int pictureIndex = context.readRowHolder().getRowIndex() - 1;
        try {
            // 处理图片引用
            if (examInfoImportVo.getImage() != null && examInfoImportVo.getImage().startsWith("=_xlfn.DISPIMG(") || examInfoImportVo.getImage().startsWith("=DISPIMG(")) {
                // 使用行号作为key获取对应的图片URL
                String ossUrl = pictureMap.get("picture_" + pictureIndex);
                if (ossUrl != null) {
                    examInfoImportVo.setImage(ossUrl);
                }
            }
            // 验证是否存在这个用户
            if (ObjectUtil.isNull(examInfoVo)) {
                BYKTExamInfoBo exerciseBo = BeanUtil.toBean(examInfoImportVo, BYKTExamInfoBo.class);
                ValidatorUtils.validate(exerciseBo);
                if (examInfoImportVo.getAffiliationIp() != null && !examInfoImportVo.getAffiliationIp().isEmpty()) {
                    Long l = geographyInfoService.selectName(examInfoImportVo.getAffiliationIp());
                    if (l != 0L) {
                        exerciseBo.setAffiliationIp(l);
                    }
                }

                if (examInfoImportVo.getInformationType() != null && !examInfoImportVo.getInformationType().isEmpty()) {
                    if ("考试大纲".equals(examInfoImportVo.getInformationType())) {
                        exerciseBo.setInformationType("1");
                    }
                    if ("历年分数线".equals(examInfoImportVo.getInformationType())) {
                        exerciseBo.setInformationType("2");
                    }
                    if ("考试政策".equals(examInfoImportVo.getInformationType())) {
                        exerciseBo.setInformationType("3");
                    }
                    if ("招生计划".equals(examInfoImportVo.getInformationType())) {
                        exerciseBo.setInformationType("4");
                    }
                }

                examInfoService.insertByBo(exerciseBo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(exerciseBo.getTitle()).append(" 导入成功");
            } else if (isUpdateSupport) {
                BYKTExamInfoBo exerciseBo = BeanUtil.toBean(examInfoImportVo, BYKTExamInfoBo.class);
                exerciseBo.setId(exerciseBo.getId());
                if (examInfoImportVo.getAffiliationIp() != null && !examInfoImportVo.getAffiliationIp().isEmpty()) {
                    Long l = geographyInfoService.selectName(examInfoImportVo.getAffiliationIp());
                    if (l != 0L) {
                        exerciseBo.setAffiliationIp(l);
                    }
                }

                if (examInfoImportVo.getInformationType() != null && !examInfoImportVo.getInformationType().isEmpty()) {
                    if ("考试大纲".equals(examInfoImportVo.getInformationType())) {
                        exerciseBo.setInformationType("1");
                    }
                    if ("历年分数线".equals(examInfoImportVo.getInformationType())) {
                        exerciseBo.setInformationType("2");
                    }
                    if ("考试政策".equals(examInfoImportVo.getInformationType())) {
                        exerciseBo.setInformationType("3");
                    }
                    if ("招生计划".equals(examInfoImportVo.getInformationType())) {
                        exerciseBo.setInformationType("4");
                    }
                }
                examInfoService.updateByBo(exerciseBo);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、账号 ").append(exerciseBo.getTitle()).append(" 更新成功");
            } else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、账号 ").append(examInfoImportVo.getTitle()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、账号 " + HtmlUtil.cleanHtmlTag(examInfoImportVo.getTitle()) + " 导入失败：";
            String message = e.getMessage();
            if (e instanceof ConstraintViolationException cvException) {
                message = StreamUtils.join(cvException.getConstraintViolations(), ConstraintViolation::getMessage, ", ");
            }
            failureMsg.append(msg).append(message);
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<BYKTExamInfoImportVo> getExcelResult() {
        return new ExcelResult<>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<BYKTExamInfoImportVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
